package com.tz.dao;

import com.tz.entity.Category;
import com.tz.entity.Product;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by Tinyang on 2016/7/27.
 */
@Repository
public class ProductDaoImpl implements ProductDao {
    @Autowired
    private SessionFactory sessionFactory;
    private Session getSession(){
        return  sessionFactory.getCurrentSession();
    }
    @Override
    @Transactional
    public Product selectProduct(long product_id) {
        Product product= (Product) this.getSession().get(Product.class,product_id);
        return product;
    }

    @Override
    @Transactional
    public List<Product> selectAllProducts() {
        List<Product> products;
        String hql="from Product";
        products=this.getSession().createQuery(hql).list();
        return products;
    }

    @Override
    @Transactional
    public List<Category> selectAllCategories() {
        List<Category> categories;
        String hql="from Category where parent=null";
        categories=this.getSession().createQuery(hql).list();
        return categories;
    }

    @Override
    @Transactional
    public List<Product> selectProductsByCId(long category_id) {
        List<Product>products;
        String hql="from Product where category=:id";
        products=this.getSession().createQuery(hql).setLong("id",category_id).list();
        return products;
    }
}
